package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.OrdersService;
import com.sky.service.ReportService;
import com.sky.service.UserService;
import com.sky.service.WorkspaceService;
import com.sky.utils.RedisUtil;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.SortParameters;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.sky.constant.RedisConstant.TOTAL_KEY;

/**
 * @Author : xiongke
 * @Description:
 * @Date: 2024/9/5
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Resource
    WorkspaceService workspaceService;

    @Resource
    OrdersMapper ordersMapper;

    @Resource
    UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;


    /**
     * 获取日期列表
     *
     * @param begin 开始
     * @param end   结束
     * @return {@link ArrayList}<{@link LocalDate}>
     */
    private ArrayList<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> list = new ArrayList<>();
        list.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            list.add(begin);
        }
        return list;
    }


    /**
     * 营业统计
     *
     * @param begin 开始
     * @param end   结束
     * @return {@link TurnoverReportVO}
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        long start = System.currentTimeMillis();
        String key = TOTAL_KEY + begin + "" + end + "turnoverStatistics";
        String resultString = (String) redisUtil.get(key);
        TurnoverReportVO result = JSON.parseObject(resultString, new TypeReference<TurnoverReportVO>() {});
        if (result != null){
            System.out.println("redis查询营业额统计时间：{}" + (System.currentTimeMillis() - start));
            return result;
        }
        // 获取天数
        ArrayList<LocalDate> list = getDateList(begin, end);
        String dateList = StringUtils.join(list, ",");
        // 获取每日销售额
        ArrayList<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : list) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = ordersMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        TurnoverReportVO reportVO = TurnoverReportVO.builder()
                .dateList(dateList)
                .turnoverList(StringUtils.join(turnoverList, ",")).build();
        String jsonString = JSON.toJSONString(reportVO);
        redisUtil.setNx(key,jsonString,24L, TimeUnit.HOURS);
        System.out.println("数据库查询营业额数据时间：{}" + (System.currentTimeMillis() - start));
        return reportVO;
    }


    /**
     * 用户统计
     *
     * @param begin 开始
     * @param end   结束
     * @return {@link UserReportVO}
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        long start = System.currentTimeMillis();
        String key = TOTAL_KEY + begin + "" + end + "user";
        String resultJson = (String) redisUtil.get(key);
        UserReportVO result = JSON.parseObject(resultJson, new TypeReference<UserReportVO>() {});
        if (result !=null){
            System.out.println("redis查询用户统计时间：{}" + (System.currentTimeMillis() - start));
            return result;
        }
        // 获取天数
        ArrayList<LocalDate> list = getDateList(begin, end);
        String dateList = StringUtils.join(list, ",");
        // 获取当前用户总量
        ArrayList<String> totalUserList = new ArrayList<>();
        for (LocalDate localDate : list) {
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("end", endTime);
            String userTotal = userMapper.sumUserByMap(map);
            userTotal = userTotal == null ? "0" : userTotal;
            totalUserList.add(userTotal);
        }
        // 获取当日用户新增
        ArrayList<String> newUserList = new ArrayList<>();
        for (LocalDate localDate : list) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            String userTotal = userMapper.sumUserByMap(map);
            userTotal = userTotal == null ? "0" : userTotal;
            newUserList.add(userTotal);
        }
        UserReportVO userReportVO = UserReportVO.builder()
                .totalUserList(StringUtils.join(totalUserList, ","))
                .dateList(dateList)
                .newUserList(StringUtils.join(newUserList, ",")).build();
        System.out.println("数据库查询时间：{}" + (System.currentTimeMillis() - start));
        redisUtil.setNx(key, JSON.toJSONString(userReportVO),24L , TimeUnit.HOURS);
        return userReportVO;
    }

    /**
     * 订单统计
     *
     * @param begin 开始
     * @param end   结束
     * @return {@link OrderReportVO}
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        long start = System.currentTimeMillis();
        String key = TOTAL_KEY + begin + "" + end;
        String resultJson = (String) redisUtil.get(key);
        OrderReportVO result = JSON.parseObject(resultJson, new TypeReference<OrderReportVO>() {});
        if (result != null) {
            System.out.println("redis查询订单统计时间：" + (System.currentTimeMillis() - start));
            return result;
        }
        ArrayList<LocalDate> list = getDateList(begin, end);
        String dateList = StringUtils.join(list, ",");
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate localDate : list) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            // 获取每日订单数量
            HashMap<Object, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            String orderCount = ordersMapper.countByMap(map);
            orderCountList.add(Integer.parseInt(orderCount));
            // 获取每日有效订单
            map.put("status", Orders.COMPLETED);
            String validOrderCount = ordersMapper.countByMap(map);
            validOrderCountList.add(Integer.parseInt(validOrderCount));
        }
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        OrderReportVO reportVO = OrderReportVO.builder()
                .dateList(dateList)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        System.out.println("数据库查询订单统计时间：" + (System.currentTimeMillis() - start));
        redisUtil.setNx(key, JSON.toJSONString(reportVO),24L,TimeUnit.HOURS);
        return reportVO;
    }

    /**
     * 前 10 名
     *
     * @param begin 开始
     * @param end   结束
     * @return {@link SalesTop10ReportVO}
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        long start = System.currentTimeMillis();
        String key = TOTAL_KEY + begin + "" + end + "top10";
        String resultJson = (String) redisUtil.get(key);
        SalesTop10ReportVO result = JSON.parseObject(resultJson, new TypeReference<SalesTop10ReportVO>() {});
        if (result !=null){
            System.out.println("redis查询top10统计时间：{}" + (System.currentTimeMillis() - start));
            return result;
        }
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> top10 = ordersMapper.getTop10(beginTime, endTime);
        List<String> list = top10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> collect = top10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        SalesTop10ReportVO top10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(list, ","))
                .numberList(StringUtils.join(collect, ","))
                .build();
        redisUtil.setNx(key, JSON.toJSONString(top10ReportVO),24L,TimeUnit.HOURS);
        System.out.println("数据库查询top10统计时间：{}" + (System.currentTimeMillis() - start));
        return top10ReportVO;
    }

    /*
     * 导出Excel数据
     * */
    @Override
    @SneakyThrows
    public void export(HttpServletResponse response) {
        //查询出对应的数据
        // 近30天时间
        LocalDate now = LocalDate.now();
        LocalDateTime begin = LocalDateTime.of(now.minusDays(30), LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(now.minusDays(1), LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);
        // 使用poi组装表格
        // 1、获取模版
        InputStream resource = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        // 2、获取到表格
        XSSFWorkbook excel = new XSSFWorkbook(resource);
        XSSFSheet sheet1 = excel.getSheet("sheet1");
        //3、开始组装
        sheet1.getRow(1).getCell(1).setCellValue("时间：" + now.minusDays(30) + "至" + now.minusDays(1));
        sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
        sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
        sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
        sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
        sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

        // 组装30天 每天的内容
        LocalDate date = now.minusDays(30);
        for (int i = 0; i < 30; i++) {
            LocalDate beginDate = date.plusDays(i);
            BusinessDataVO vo = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(beginDate, LocalTime.MAX));
            XSSFRow row = sheet1.getRow(7 + i);
            row.getCell(1).setCellValue(String.valueOf(beginDate));
            row.getCell(2).setCellValue(vo.getTurnover());
            row.getCell(3).setCellValue(vo.getValidOrderCount());
            row.getCell(4).setCellValue(vo.getOrderCompletionRate());
            row.getCell(5).setCellValue(vo.getUnitPrice());
            row.getCell(6).setCellValue(vo.getNewUsers());
        }
        // 浏览器下载
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);
    }
}
